package com.xfcycle.zebrabikegp.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.gson.Gson;
import com.xfcycle.zebrabikegp.util.ActivitiesStackUtil;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;
import com.xfcycle.zebrabikegp.util.HandleDataByWebUtil;

import java.util.Map;

public class RootActivity extends FragmentActivity implements OnMapReadyCallback {

    public static final String LOGIN_ACTIVITY = "com.xfcycle.zebrabikegp.activity.LoginActivity";
    public static final String FIND_PASSWORD_ADDRESS_ACTIVITY = "com.xfcycle.zebrabikegp.activity.FindPasswordAddressActivity";
    public static final String FIND_PASSWORD_PASSWORD_ACTIVITY = "com.xfcycle.zebrabikegp.activity.FindPasswordPasswordActivity";
    public static final String REGIST_ADDRESS_ACTIVITY = "com.xfcycle.zebrabikegp.activity.RegistAddressActivity";
    public static final String REGIST_PASSWORD_ACTIVITY = "com.xfcycle.zebrabikegp.activity.RegistPasswordActivity";

    public static final String HOME_MAP_ACTIVITY = "com.xfcycle.zebrabikegp.activity.HomeMapActivity";

    public static final String MY_PROFILE_ACTIVITY = "com.xfcycle.zebrabikegp.activity.MyProfileActivity";
    public static final String MY_BIKE_ACTIVITY = "com.xfcycle.zebrabikegp.activity.MyBikeActivity";
    public static final String SETTING_ACTIVITY = "com.xfcycle.zebrabikegp.activity.SettingActivity";
    public static final String DEBUG_ACTIVITY = "com.xfcycle.zebrabikegp.activity.DebugActivity";
    public static final String SPORT_DATA_ACTIVITY = "com.xfcycle.zebrabikegp.activity.SportDataActivity";
    public static final String ABOUT_ACTIVITY = "com.xfcycle.zebrabikegp.activity.AboutActivity";
    public static final String BIKE_SETTING_ACTIVITY = "com.xfcycle.zebrabikegp.activity.BikeSettingActivity";
    public static final String BIKE_TEST_ACTIVITY = "com.xfcycle.zebrabikegp.activity.BsTestActivity";
    public static final String BIKE_FRAME_INFO = "com.xfcycle.zebrabikegp.activity.BikeInfoActivity";

    public static final String BLUETOOTH_SEARCH_ACTIVITY = "com.xfcycle.zebrabikegp.activity.BluetoothSearchActivity";

    public static final String GEAR_POWER_OUTPUT_ACTIVITY = "com.xfcycle.zebrabikegp.activity.BsGearPowerOutputActivity";
    public static final String SENSOR_CALIBRATION_ACTIVITY = "com.xfcycle.zebrabikegp.activity.BsSensorCalibrationActivity";
    public static final String ADJUST_BIKE_DORMANCY_ACTIVITY = "com.xfcycle.zebrabikegp.activity.BsSleepTimeActivity";
    public static final String BLUETOOTH_KEY_ACTIVITY = "com.xfcycle.zebrabikegp.activity.BsBlueToothKeyActivity";
    public static final String SPEED_LIMIT_ACTIVITY = "com.xfcycle.zebrabikegp.activity.BsSpeedLimitActivity";
    public static final String ALARM_ACTIVITY = "com.xfcycle.zebrabikegp.activity.BsAlarmActivity";
    public static final String LOW_BATTERY_LEVEL_FOLDBACK_ACTIVITY = "com.xfcycle.zebrabikegp.activity.BsLowBatteryLevelFoldbackActivity";
    public static final String REGENERATION_BRAKE_ACTIVITY = "com.xfcycle.zebrabikegp.activity.BsRegenerationBrakeActivity";

    public static final String BIKE_NICKNAME_CHANGE_ACTIVITY = "com.xfcycle.zebrabikegp.activity.BikeNikenameChangeActivity";

    public static final String MY_PROFILE_MOBILE_ACTIVITY = "com.xfcycle.zebrabikegp.activity.MyProfileMobileActivity";
    public static final String MY_PROFILE_EMAIL_ACTIVITY = "com.xfcycle.zebrabikegp.activity.MyProfileEmailActivity";
    public static final String MY_PROFILE_GENDER_ACTIVITY = "com.xfcycle.zebrabikegp.activity.MyProfileGenderActivity";
    public static final String MY_PROFILE_NAME_ACTIVITY = "com.xfcycle.zebrabikegp.activity.MyProfileNameActivity";
    public static final String MY_PROFILE_PASSWORD_ACTIVITY = "com.xfcycle.zebrabikegp.activity.MyProfilePasswordActivity";

    public static final String ALARM_LIST_ACTIVITY = "com.xfcycle.zebrabikegp.activity.AlarmListActivity";
    public static final String ALARM_MAP_ACTIVITY = "com.xfcycle.zebrabikegp.activity.AlarmMapActivity";

    //请求标志，标明该message属于哪一个网络请求返回
    public static final int REQUEST_SIGN_GET_EMAIL_CAPTCHA = 10001;
    public static final int REQUEST_SIGN_GET_MOBILE_CAPTCHA = 10014;
    public static final int REQUEST_SIGN_VERIFICATE_EMAIL_CAPTCHA = 10002;
    public static final int REQUEST_SIGN_REGIST = 10003;
    public static final int REQUEST_SIGN_RESETPASSWORD = 10004;
    public static final int REQUEST_SIGN_LOGIN = 10005;
    public static final int REQUEST_SIGN_HOME_MAP_GET_USER_BIKE_INFO = 10006;
    public static final int REQUEST_SIGN_GET_USER_INFO_BY_UID = 10007;
    public static final int REQUEST_SIGN_GET_BIKE_INFO_BY_CID = 10008;
    public static final int REQUEST_SIGN_GET_BIKE_BID_BY_BNAME_BIND_USER = 10009;
    public static final int REQUEST_SIGN_GET_BIKE_BID_BY_BNAME_CURRENT_CONN = 10017;
    public static final int REQUEST_SIGN_RELEASE_BIKE_BY_CID = 10010;
    public static final int REQUEST_SIGN_CHANGE_BIKE_NICKNAME_BY_CID = 10011;
    public static final int REQUEST_SIGN_RESET_BIKE_BY_CID = 10012;
    public static final int REQUEST_SIGN_LOGOUT = 10013;
    public static final int REQUEST_SIGN_CHANGE_MOBILE_NUM = 10015;
    public static final int REQUEST_SIGN_CHANGE_EMAIL_ADDRESS = 10016;
    public static final int REQUEST_SIGN_CHANGE_GENDER = 10018;
    public static final int REQUEST_SIGN_CHANGE_USERNAME = 10019;
    public static final int REQUEST_SIGN_CHANGE_PASSWORD = 10020;
    public static final int REQUEST_SIGN_BIND_BIKE_BY_CID = 10021;
    public static final int REQUEST_SIGN_GET_BIKE_QRCODE = 100022;
    public static final int REQUEST_SIGN_GET_BIKE_INFO_BY_NAME = 100023;
    public static final int REQUEST_SIGN_HOME_MAP_GET_USER_BIKE_INFO_BY_ALARM = 100024;
    public static final int REQUEST_SIGN_REMOVE_ALARM = 100025;

    //带结果页面跳转 请求码
    public static final int REQUEST_CODE_FIND_BIKE_QRCODE = 20001;

    public static final int REQUEST_CODE_GET_SYSTEM_PICTURE = 20002;
    public static final int REQUEST_CODE_GET_SYSTEM_CAMERA = 20003;

    public static final int REQUEST_CODE_CHANGE_BIKE_NICKNAME = 20004;
    public static final int REQUEST_CODE_MY_BIKE = 20005;

    public static final int REQUEST_CODE_MY_PROFILE_MOBILE_CHANGE = 20006;
    public static final int REQUEST_CODE_MY_PROFILE_EMAIL_CHANGE = 20007;
    public static final int REQUEST_CODE_MY_PROFILE_GENDER_CHANGE = 20008;
    public static final int REQUEST_CODE_MY_PROFILE_NAME_CHANGE = 20009;
    public static final int REQUEST_CODE_MY_PROFILE_PASSWORD_CHANGE = 20010;
    public static final int REQUEST_CODE_MY_PROFILE = 20011;
    public static final int REQUEST_CODE_SPORT_DATA = 20012;

    public static final int REQUEST_CODE_BLUETOOTH_SEARCH = 20013;
    public static final int PLACE_AUTOCOMPLETE_REQUEST_CODE = 20014;

    public Gson gson = new Gson();

    //SharePreferences的名字
    public static final String APP_INFO_SP_NAME = "app_information";

    private Handler handlerWebMessage = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            if (0 == msg.arg1) {
                Toast.makeText(RootActivity.this, "Network access failure..", Toast.LENGTH_SHORT).show();
                return;
            }
            if (null == msg.obj) {
                Toast.makeText(RootActivity.this, "Network access failure..", Toast.LENGTH_SHORT).show();
                return;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if ("defeat".equals(msg.obj.toString())) {
                        Toast.makeText(RootActivity.this, "Failed to connect the server..", Toast.LENGTH_SHORT).show();
                    }

                    dealDataFromWeb(msg);
                }
            });
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        ActivitiesStackUtil.getInstance().push(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //判断当前所有窗体数量 当数量为一时 关闭蓝牙BLE连接
        if (ActivitiesStackUtil.getInstance().size() == 1) {
            HandleDataByBLEUtil.deleteInstance();
        }

        ActivitiesStackUtil.getInstance().pop();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
    }

    /**
     * 处理从网络获得的数据，需子类重写该方法
     */
    public void dealDataFromWeb(Message webMsg) {
    }

    /**
     * 横竖屏切换调用的配置时方法
     */
    public void onConfigurationChanged(Configuration newConfig) {
        try {
            super.onConfigurationChanged(newConfig);
            if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                Log.v("Himi", "onConfigurationChanged_ORIENTATION_LANDSCAPE");
            } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                Log.v("Himi", "onConfigurationChanged_ORIENTATION_PORTRAIT");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 页面跳转方法，分别传入窗体路径，需要携带的值，结果ID
     */
    public void activityChange(String activityPath, Map<String, String> data, Integer resultId) {
        Intent int_Change_Activity = new Intent();
        int_Change_Activity.setClassName(this, activityPath);

        //传入所需要携带的参数
        if (null != data) {
            Bundle bundle = new Bundle();
            for (Map.Entry<String, String> map : data.entrySet()) {
                bundle.putString(map.getKey(), map.getValue());
            }
            int_Change_Activity.putExtras(bundle);
        }

        //传入结果ID
        if (null != resultId) {
            startActivityForResult(int_Change_Activity, resultId);
            return;
        }

        startActivity(int_Change_Activity);
    }

    /**
     * 给当前页面注册广播
     *
     * @param broadcastReceiver 自己定义的广播接收者
     */
    protected void registBroadcastReceiverAtActivity(BroadcastReceiver broadcastReceiver, String broadCastReceiverAction) {
        //设置意图过滤器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(broadCastReceiverAction);
        //注册广播
        registerReceiver(broadcastReceiver, intentFilter);
    }

    /**
     * toast消息展示
     *
     * @param text
     * @param duration
     */
    public void toast(final String text, final Integer duration) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(RootActivity.this, text, duration).show();
            }
        });
    }

    /**
     * 关闭窗体
     */
    public void closeActivity() {
        finish();
    }

    /**
     * 从服务器获取数据
     *
     * @param
     */
    class GetJsonFromWebJob extends Thread {

        private HandleDataByWebUtil handleDataByWebUtil;
        private String requestPath;
        private String requestStyle;
        private Map<String, String> params;
        private int requestSign;
        private Message msg;

        /**
         * 构造函数
         *
         * @param requestPath  请求地址
         * @param requestStyle 请求方式
         * @param params       请求参数
         * @param requestSign  请求标志
         * @param context      上下文
         */
        public GetJsonFromWebJob(String requestPath, String requestStyle, Map<String, String> params, int requestSign, Context context) {
            this.requestPath = requestPath;
            this.requestStyle = requestStyle;
            this.params = params;
            this.requestSign = requestSign;
            this.msg = handlerWebMessage.obtainMessage();
            handleDataByWebUtil = HandleDataByWebUtil.getInstance(context);
        }

        @Override
        public void run() {
            StringBuffer param = new StringBuffer();
            String lastParam = null;
            String result = "";

            if (null != params) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    param = param.append(entry.getKey())
                            .append("=")
                            .append(entry.getValue())
                            .append("&");
                }
                lastParam = param.subSequence(0, param.length() - 1).toString();
            }
            if ("get".equals(requestStyle)) {
                result = handleDataByWebUtil.getJsonFromWebByGet(requestPath, lastParam);
            }
            if ("post".equals(requestStyle)) {
                result = handleDataByWebUtil.getJsonFromWebByPost(requestPath, lastParam);
            }
            if ("put".equals(requestStyle)) {
                result = handleDataByWebUtil.getJsonFromWebByPut(requestPath, lastParam);
            }

            Log.e("RootActivity", "run: " + result);

            msg.arg1 = 1;
            msg.obj = result;
            msg.what = requestSign;
            msg.sendToTarget();
        }
    }
}
